package com.kerwin.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {

    public String payment_ok(Integer id){
        return "线程池：" + Thread.currentThread().getName() + "paymen_ok; id = " + id + ";ok";
    }

    @HystrixCommand(fallbackMethod = "payment_timeout_handler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String payment_timeout(Integer id){
        try {
//            int x = 10 / 0;
            int sleepTime = 3;
            TimeUnit.SECONDS.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + "payment_timeout; id = " + id + ";timeout";
    }

    public String payment_timeout_handler(Integer id){
        return "线程池：" + Thread.currentThread().getName() + "payment_timeout_hander; id = " + id + ";超时/异常";
    }

    @HystrixCommand(fallbackMethod = "payment_hystrix_breaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),// 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率达到多少时跳闸
    })
    public String payment_hystrix_breaker(Integer id){
        if(id < 0){
            throw  new RuntimeException("id不能为负数");
        }
        String result = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t 调用成功，流水号：" + result;
    }

    public String payment_hystrix_breaker_fallback(Integer id){
        return "id不能为负数，请稍后再试：" + id;
    }
}
